"""
道路交通事件智能分类与优先级管理系统
主应用文件
"""

from data_collection.data_collector import DataCollector
from text_preprocess.text_processor import TextProcessor
from classification.classifier import EventClassifier
from priority_evaluation.evaluator import PriorityEvaluator
from results_manage.results_manager import ResultsManager
from system_config.config_manager import ConfigManager


class EventClassifierSystem:
    def __init__(self):
        self.data_collector = DataCollector()
        self.text_processor = TextProcessor()
        self.event_classifier = EventClassifier()
        self.priority_evaluator = PriorityEvaluator()
        self.results_manager = ResultsManager()
        self.config_manager = ConfigManager()
        
        # 初始化系统
        self._initialize_system()
    
    def _initialize_system(self):
        """
        初始化系统
        """
        print("正在初始化道路交通事件智能分类与优先级管理系统...")
        
        # 加载配置
        system_config = self.config_manager.get_config('system')
        print(f"系统名称: {system_config.get('name', 'Unknown')}")
        print(f"系统版本: {system_config.get('version', 'Unknown')}")
        
        # 初始化模型参数
        svm_params = self.config_manager.get_model_params('svm')
        print(f"SVM模型参数: {svm_params}")
        
        dt_params = self.config_manager.get_model_params('decision_tree')
        print(f"决策树模型参数: {dt_params}")
        
        print("系统初始化完成\n")
    
    def run_demo(self):
        """
        运行演示流程
        """
        print("开始运行演示流程...")
        
        # 1. 数据采集
        print("1. 数据采集阶段")
        manual_data = {
            "title": "交通事故",
            "description": "在中山路与解放路交叉口发生一起两车相撞事故，造成交通拥堵",
            "source": "日常巡查",
            "timestamp": "2023-05-15 14:30:00"
        }
        self.data_collector.collect_from_manual(manual_data)
        
        api_data = [
            {
                "title": "道路施工",
                "description": "南京路从人民广场到淮海路段进行道路施工，预计工期一个月",
                "source": "110报警",
                "timestamp": "2023-05-15 15:20:00"
            },
            {
                "title": "设施故障",
                "description": "地铁2号线人民广场站电梯故障停运，乘客需步行上下楼梯",
                "source": "舆情采集",
                "timestamp": "2023-05-15 16:10:00"
            }
        ]
        self.data_collector.collect_from_api(api_data)
        
        raw_data = self.data_collector.get_raw_data()
        print(f"采集到 {len(raw_data)} 条原始数据")
        
        # 2. 文本预处理
        print("\n2. 文本预处理阶段")
        processed_texts = []
        for data in raw_data:
            features = self.text_processor.extract_features(data['description'])
            processed_texts.append(features['cleaned_text'])
            print(f"  原文: {data['description']}")
            print(f"  处理后: {features['cleaned_text']}")
        
        # 3. 事件分类
        print("\n3. 事件分类阶段")
        # 模拟训练数据
        train_texts = [
            "道路拥堵严重，车辆行驶缓慢",
            "南京路进行道路施工，预计工期一个月",
            "在中山路与解放路交叉口发生一起两车相撞事故",
            "地铁2号线人民广场站电梯故障停运",
            "今天天气很好，适合出行"
        ]
        train_labels = ['拥堵', '施工', '交通事故', '设施故障', '其他']
        
        # 训练分类模型
        if self.event_classifier.train(train_texts, train_labels):
            print("分类模型训练成功")
            
            # 对采集的数据进行分类
            for i, text in enumerate(processed_texts):
                label, confidence = self.event_classifier.predict(text)
                print(f"  数据 {i+1} 分类结果: {label} (置信度: {confidence:.2f})")
        else:
            print("分类模型训练失败")
            return
        
        # 4. 优先级评估
        print("\n4. 优先级评估阶段")
        # 模拟训练数据
        training_data = [
            {'id': 'EV001', 'event_type': '交通事故', 'location_type': '主干道', 'time_period': '高峰时段', 'impact_scope': 5},
            {'id': 'EV002', 'event_type': '施工', 'location_type': '次干道', 'time_period': '平峰时段', 'impact_scope': 3},
            {'id': 'EV003', 'event_type': '设施故障', 'location_type': '地铁站', 'time_period': '高峰时段', 'impact_scope': 4}
        ]
        training_labels = ['紧急', '一般', '紧急']
        
        # 训练评估模型
        if self.priority_evaluator.train(training_data, training_labels):
            print("优先级评估模型训练成功")
            
            # 对分类结果进行优先级评估
            for i, data in enumerate(raw_data):
                event_data = {
                    'id': f"EV100{i+1}",
                    'event_type': '交通事故' if '事故' in data['description'] else ('施工' if '施工' in data['description'] else '其他'),
                    'location_type': '主干道',
                    'time_period': '高峰时段',
                    'impact_scope': 4
                }
                priority, confidence = self.priority_evaluator.evaluate(event_data)
                print(f"  事件 {data['title']} 优先级: {priority} (置信度: {confidence:.2f})")
                
                # 5. 结果管理
                result_data = {
                    'id': f"RES100{i+1}",
                    'title': data['title'],
                    'description': data['description'],
                    'event_type': '交通事故' if '事故' in data['description'] else ('施工' if '施工' in data['description'] else '其他'),
                    'priority': priority,
                    'timestamp': data['timestamp']
                }
                self.results_manager.save_result(result_data)
        else:
            print("优先级评估模型训练失败")
            return
        
        # 6. 结果查询和统计
        print("\n5. 结果管理阶段")
        all_results = self.results_manager.get_all_results()
        print(f"共保存 {len(all_results)} 条结果")
        
        stats = self.results_manager.get_statistics()
        print("统计信息:")
        print(f"  总数: {stats.get('total_count', 0)}")
        print(f"  事件类型分布: {stats.get('event_type_counts', {})}")
        print(f"  优先级分布: {stats.get('priority_counts', {})}")
        
        print("\n演示流程运行完成")


def main():
    # 创建系统实例
    system = EventClassifierSystem()
    
    # 运行演示
    system.run_demo()


if __name__ == "__main__":
    main()